from __future__ import absolute_import
#import contextlib
import os
from forest.registry import register_tool
from forest.tool import Tool
import logging
logger = logging.getLogger('tools.system.cd')

@register_tool('system.cd')
class cd(object):
    ''' A context manager that changes the current directory.

        For example::

            with cd(path):

                # ... do stuff in path ...

    '''
    def __init__(self, path):
        self.path = path
        self.previous_path = os.getcwd()

    def __enter__(self):
        logger.debug('Change directory: %s', self.path)
        os.chdir(self.path)

    def __exit__(self, exc_type, exc_value, traceback):
        os.chdir(self.previous_path)
        logger.debug('Change back directory: %s', self.previous_path)
